import React from 'react';
export default class Index extends React.Component<any, any, any> {
  scrollBox: any = React.createRef();
  state = { start: 0 };
  handleScroll = () => {
    const { itemSize } = this.props;
    const { scrollTop } = this.scrollBox.current;
    const start = Math.floor(scrollTop / itemSize);
    this.setState({ start });
  };
  render() {
    const { height, width, itemCount, itemSize, renderItem } = this.props;
    const { start } = this.state;
    let end = start + Math.floor(height / itemSize) + 1;
    end = end > itemCount ? itemCount : end;
    const visibleList = new Array(end - start)
      .fill(0)
      .map((item, index) => ({ index: start + index }));
    const style = { position: 'absolute', top: 0, left: 0, width: '100%', height: itemSize };
    return (
      <div
        style={{ overflow: 'auto', willChange: 'transform', height, width }}
        ref={this.scrollBox}
        onScroll={this.handleScroll}
      >
        <div style={{ position: 'absolute', width: '100%', height: `${itemCount * itemSize}px` }}>
          {visibleList.map(({ index }) =>
            renderItem({ index, style: { ...style, top: itemSize * index } }),
          )}
        </div>
      </div>
    );
  }
}
